<template>
    <BasicInformation :title="title" @action="handleAction" :primary-actions="mainActions"></BasicInformation>
    <div class="add">
       <div class="common-layout">
         <el-container>
           <el-main>
             <el-row>
               <el-col :span="24">
                 <div class="grid-content ep-bg-purple">
                   <h4>基本信息</h4>
                   <el-form :inline="true" :model="writeOff" :rules="rules" status-icon ref="formRef">
                     <el-form-item label="单据编号" prop="docCode">
                 <el-input 
                     v-model="writeOff.docCode"
                     style="width: 240px"
                     placeholder="请输入单据编号"
                     clearable
                     :disabled="true"
                     />
                         </el-form-item>
                     <!-- 客户 -->
                     <el-form-item label="客户" prop="cid" v-if="writeOff.targetType != 2 && writeOff.targetType != 5"> 
                             <el-select
                               v-model="writeOff.cid" 
                               placeholder="请选择客户"
                               style="width: 240px"
                               clearable
                               filterable
                             >
                               <el-option
                                 v-for="customer in customerList"
                                 :key="customer.id"
                                 :label="`${customer.code} - ${customer.name}`"
                                 :value="customer.id"
                               />
                             </el-select>
                      </el-form-item>
                      <el-form-item label="供应商" prop="pid" v-if="writeOff.targetType == 2||writeOff.targetType == 5">
                          <el-select
                            v-model="writeOff.pid"
                            placeholder="请选择供应商"
                            style="width: 240px"
                            clearable
                            filterable
                            >
                      <el-option
                           v-for="provider in providerList"
                            :key="provider.id"
                            :label="`${provider.code} - ${provider.name}`"
                             :value="provider.id"
                             />
                      </el-select>
                      </el-form-item>
                            <el-form-item 
                                v-if="writeOff.targetType == 4" 
                                label="转入结算客户" 
                                prop="transferInCid"
                              >
                                <el-select
                                  v-model="writeOff.transferInCid"
                                  placeholder="请选择转入客户"
                                  style="width: 240px"
                                  clearable
                                  filterable
                                >
                                  <el-option
                                    v-for="customer in customerList"
                                    :key="customer.id"
                                    :label="`${customer.code} - ${customer.name}`"
                                    :value="customer.id"
                                  />
                                </el-select>
                              </el-form-item>

                    <!-- 核销类型 -->
                     <el-form-item label="核销类型">
                        <el-select v-model="writeOff.targetType"  placeholder="请选择核销类型" clearable filterable style="width:240px">
                        <el-option v-for="item in writeoffTypeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                        </el-option>
                        </el-select>
                        
                     
                     </el-form-item>
                     
                     <!-- 核销日期 -->
                     <el-form-item label="单据日期" prop="docDate">
                       <el-date-picker
                         v-model="writeOff.docDate"
                         type="date"
                         placeholder="请选择日期"
                         value-format="YYYY-MM-DD"
                         :disabled-date="disabledDate"
                       />
                     </el-form-item>
                     <!-- 业务员 -->
                     <el-form-item label="业务员" prop="uid">
                            <el-select
                              v-model="writeOff.uid" 
                              placeholder="请选择客户"
                              style="width: 240px"
                              clearable
                              filterable
                            >
                              <el-option
                                v-for="user in userList"
                                :key="user.id"
                                :label="user.name"
                                :value="user.id"
                              />
                            </el-select>
                          </el-form-item>

 
                     <!-- 部门 -->
                     <el-form-item label="部门" prop="did">
                      <el-select
                        v-model="writeOff.did"
                        placeholder="请选择部门"
                        style="width: 240px;"
                        clearable
                      >
                        <el-option 
                          v-for="dept in deptList"
                          :key="dept.id"
                          :label="dept.name"
                          :value="dept.id"
                        />
                      </el-select>
                    </el-form-item>
                   </el-form>
                 </div>
               </el-col>
             </el-row>
           </el-main>
         </el-container>
       </div>
     </div>

   <!-- 预收单据核销区 -->
<div class="source-info" v-if="writeOff.targetType == 1">
  <div class="toolbar">
    <el-button type="primary" @click="selectSourceOrder('advance')" :disabled="writeOff.cid==null">选择源单</el-button>
  </div>
  
  <el-table :data="sourceOrdersA" border style="width: 100%">
    <el-table-column label="源单日期" prop="orderDate" width="120" align="center"/>
    <el-table-column label="源单类型" width="120" align="center">
      <template #default="scope">{{ getOrderType(scope.row.orderType) }}</template>
    </el-table-column>
    <el-table-column label="源单编号" prop="orderCode" width="180" align="center"/>
    <el-table-column label="客户名称" width="150" align="center">
      <template #default="scope">{{ scope.row.customerName }}</template>
    </el-table-column>
    <el-table-column label="预收金额" width="120" align="center">
      <template #default="scope">¥{{ scope.row.advanceAmount?.toFixed(2) }}</template>
    </el-table-column>
     <el-table-column label="源单已核销金额" width="150" align="center">
      <template #default="scope">¥{{ scope.row.settledAmount?.toFixed(2) }}</template>
    </el-table-column>
       <el-table-column label="源单未核销金额" width="150" align="center">
      <template #default="scope">¥{{ scope.row.unsettledAmount?.toFixed(2) }}</template>
    </el-table-column>
    <el-table-column label="本次核销" width="150" align="center">
      <template #default="scope">
        <el-input-number 
          v-model="scope.row.currentSettle"
          :min="0" 
          :max="getMaxSettle(scope.row)"
          @change="syncPaymentAmount"
          :precision="2"
          controls-position="right"
        />
      </template>
    </el-table-column>
    <el-table-column label="操作" width="80" align="center">
      <template #default="scope">
        <el-button link type="danger" @click="removeSourceOrder(scope.row, 'advance')">移除</el-button>
      </template>
    </el-table-column>
  </el-table>
</div>

 <!-- 预付单据核销区 -->
<div class="source-info" v-if="writeOff.targetType == 2">
  <div class="toolbar">
    <el-button type="primary" @click="selectSourceOrder('prepay')" :disabled="writeOff.pid==null">选择源单</el-button>
  </div>
  
  <el-table :data="sourceOrdersD" border style="width: 100%">
    <el-table-column label="源单日期" prop="orderDate" width="120" align="center"/>
    <el-table-column label="源单类型" width="120" align="center">
      <template #default="scope">{{ getOrderType(scope.row.orderType) }}</template>
    </el-table-column>
    <el-table-column label="源单编号" prop="orderCode" width="180" align="center"/>
    <el-table-column label="供应商名称" width="150" align="center">
      <template #default="scope">{{ scope.row.customerName }}</template>
    </el-table-column>
    <el-table-column label="预付金额" width="120" align="center">
      <template #default="scope">¥{{ scope.row.advanceAmount?.toFixed(2) }}</template>
    </el-table-column>
     <el-table-column label="源单已核销金额" width="150" align="center">
      <template #default="scope">¥{{ scope.row.settledAmount?.toFixed(2) }}</template>
    </el-table-column>
       <el-table-column label="源单未核销金额" width="150" align="center">
      <template #default="scope">¥{{ scope.row.unsettledAmount?.toFixed(2) }}</template>
    </el-table-column>
    <el-table-column label="本次核销" width="150" align="center">
      <template #default="scope">
        <el-input-number 
          v-model="scope.row.currentSettle"
          :min="0" 
          :max="getMaxSettle(scope.row)"
          @change="syncPaymentAmount"
          :precision="2"
          controls-position="right"
        />
      </template>
    </el-table-column>
    <el-table-column label="操作" width="80" align="center">
      <template #default="scope">
        <el-button link type="danger" @click="removeSourceOrder(scope.row, 'advance')">移除</el-button>
      </template>
    </el-table-column>
  </el-table>
</div>


<!-- 应收单据核销区 -->
<div class="source-info" v-if="writeOff.targetType == 1 ||writeOff.targetType ==4 ||writeOff.targetType ==3">
  <div class="toolbar">
    <el-button type="primary" @click="selectSourceOrder('receivable')"  :disabled="writeOff.cid==null">选择源单</el-button>
  </div>

  <el-table :data="sourceOrdersB" border style="width: 100%">
    <el-table-column label="源单日期" prop="orderDate" width="120" align="center"/>
    <el-table-column label="源单类型" width="120" align="center">
      <template #default="scope">{{ getOrderType(scope.row.orderType) }}</template>
    </el-table-column>
    <el-table-column label="源单编号" prop="orderCode" width="180" align="center"/>
    <el-table-column label="客户名称" width="150" align="center">
      <template #default="scope">{{ scope.row.customerName }}</template>
    </el-table-column>
    <el-table-column label="应收金额"  width="120" align="center">
         <template #default="scope">¥{{ scope.row.receivableAmount?.toFixed(2) }}</template>
        </el-table-column>
      <el-table-column label="源单已核销金额" width="150" align="center">
      <template #default="scope">¥{{ scope.row.settledAmount?.toFixed(2) }}</template>
    </el-table-column>
       <el-table-column label="源单未核销金额" width="150" align="center">
      <template #default="scope">¥{{ scope.row.unsettledAmount?.toFixed(2) }}</template>
    </el-table-column>
    <el-table-column label="本次核销" width="150" align="center">
      <template #default="scope">
        <el-input-number
          v-model="scope.row.currentSettle"
          :min="0"
          :max="getMaxSettle(scope.row)"
          @change="syncPaymentAmount"
          :precision="2"
          controls-position="right"
        />
      </template>
    </el-table-column>
    <el-table-column label="操作" width="80" align="center">
      <template #default="scope">
        <el-button link type="danger" @click="removeSourceOrder(scope.row, 'receivable')">移除</el-button>
      </template>
    </el-table-column>
  </el-table>
</div>

<!-- 应付单据核销区 -->
<div class="source-info" v-if="writeOff.targetType == 2||writeOff.targetType == 3||writeOff.targetType == 5">
  <div class="toolbar">
    <el-button type="primary" @click="selectSourceOrder('payable')"  :disabled="writeOff.pid==null">选择源单</el-button>
  </div>
   <el-table :data="sourceOrdersC" border style="width: 100%">
    <el-table-column label="源单日期" prop="orderDate" width="120" align="center"/>
    <el-table-column label="源单类型" width="120" align="center">
      <template #default="scope">{{ getOrderType(scope.row.orderType) }}</template>
    </el-table-column>
    <el-table-column label="源单编号" prop="orderCode" width="180" align="center"/>
    <el-table-column label="供应商名称" width="150" align="center">
      <template #default="scope">{{ scope.row.supplierName }}</template>
    </el-table-column>
    <el-table-column label="应付金额" width="120" align="center">
      <template #default="scope">¥{{ (scope.row.payableAmount || 0).toFixed(2) }}</template>
    </el-table-column>
    <el-table-column label="源单未核销金额" width="150" align="center">
      <template #default="scope">¥{{ (scope.row.unsettledAmount || 0).toFixed(2) }}</template>
    </el-table-column>
    <el-table-column label="本次核销" width="150" align="center">
      <template #default="scope">
        <el-input-number
          v-model="scope.row.currentSettle"
          :min="0"
          :max="getMaxSettle(scope.row)"
          @change="syncPaymentAmount"
          :precision="2"
          controls-position="right"
        />
      </template>
    </el-table-column>
    <el-table-column label="操作" width="80" align="center">
      <template #default="scope">
        <el-button link type="danger" @click="removeSourceOrder(scope.row, 'receivable')">移除</el-button>
      </template>
    </el-table-column>
  </el-table>
</div>

 
 
  
   <el-dialog
   v-model="dialogVisible"
   title="源单选择"
   width="80%"
   top="5vh"
 >
   <!-- 查询条件区域 -->
   <div class="dialog-header">
     <el-input 
       v-model="searchForm.code" 
       placeholder="请输入单据编号" 
       style="width: 240px;margin-right: 15px"
     />
     <span class="date-label">单据日期：</span>
     <el-date-picker
       v-model="searchForm.startDate"
       type="date"
       placeholder="开始日期"
       value-format="YYYY-MM-DD"
       style="width: 160px"
     />
     <span class="date-separator">~</span>
     <el-date-picker
       v-model="searchForm.endDate"
       type="date"
       placeholder="结束日期"
       value-format="YYYY-MM-DD"
       style="width: 160px;margin-right: 15px"
     />
     <el-button type="primary" icon="Search" @click="searchSSalesAdvanceList">查询</el-button>
     <el-button icon="Refresh" @click="resetSearch">重置</el-button>
     <el-button icon="ArrowDown">展开</el-button>
   </div>
 
   <!-- 选择状态提示 -->
   <div class="selected-info">
     <span>已选择{{ selectedCount }}项</span>
     <el-button link type="primary" @click="clearSelection">清空</el-button>
   </div>
 
   <!-- 表格区域 -->
   <el-table 
     :data="WriteOffList" 
     v-if="WriteOffList.length > 0"
    
     border 
     height="60vh"
     @selection-change="handleSelectionChange"
     
   >
     <el-table-column type="selection" width="55" align="center" />
     <el-table-column prop="docCode" label="单据编号" width="180" />
     <el-table-column prop="docDate" label="单据日期" width="120" />
     <el-table-column prop="notes" label="单据主题" width="200" />
     <el-table-column prop="cid" label="客户" width="120" />
     <el-table-column prop="did" label="业务部门" width="120" />
     <el-table-column prop="uid" label="业务员" width="120" />
     <el-table-column prop="closed" label="已关闭" width="100" align="center">
       <template #default="scope">
         <el-tag :type="scope.row.closed ? 'danger' : 'success'" size="small">
           {{ scope.row.closed ? '是' : '否' }}
         </el-tag>
       </template>
     </el-table-column>
   </el-table>
 
   <!-- 分页及操作按钮 -->
   <div class="dialog-footer">
      <!-- 分页组件 -->
      <div class="pagination-wrapper">
             <el-pagination
                 background
                 layout="prev, pager, next"
                 :total="totalItems"
                 :page-size="PopupsPageSize"
                 :current-page="PopupsPageNo"
                 @current-change="handlePageChange"
             />
         </div>
     <div class="action-buttons">
       <el-button @click="dialogVisible = false">关闭</el-button>
       <el-button type="primary" @click="confirmSelection">确定</el-button>
     </div>
   </div>
 </el-dialog>
 
 
 
 </template>
 
 
 <script setup lang="ts">
 import { ref, reactive,withKeys ,watch,computed, onMounted} from 'vue';
 import BasicInformation from '@/public-view/BasicInformation.vue';
 import type {ComponentSize, FormInstance, FormRules} from 'element-plus'
 import {ElInput, ElAutoResizer, ElTableV2} from 'element-plus'
 import type {FunctionalComponent} from 'vue'
 import type {Column, InputInstance} from 'element-plus'
 import { useRouter,useRoute } from 'vue-router';
 import type { Customer } from '@/types/public-xs/Customer';
 import axios from 'axios';
 import { ElMessageBox, ElMessage } from 'element-plus'
 import type { SalesCollection,SalesCollectionRefunddetail,SalesReceivable,SalesAdvance,SalesAdvanceDetail,SalesOrder,SalesOrderDetail,SalesAdvanceRefund,SalesAdvanceRefundDetail} from '@/types/public-xs/salesDocuments';
 import type { WriteOff,WriteoffDetail,WriteoffLink,WriteoffType } from '@/types/public-xs/WriteOff';
 import type { PublicProvider } from '@/types/public-cg/provider';
 import type { User,Department } from '@/types/rs/User';
import request from '@/util/request';
 

 let docCode=ref('')
 let sourceSheet=ref('')
 let title=ref('手动核销')
 let pageNo=ref(1)
 let pageSize=ref(5)
 let allPage=ref(0)
 let router=useRouter()

 let SalesAdvanceRefundDetailList=ref<SalesAdvanceRefundDetail[]>([])
 //销售预收单退款对象
 let salesAdvanceRefund=ref<SalesAdvanceRefund>({
    id: 0,
    docCode: 'string',
    docDate:new Date,
    cid:  null,
    uid: 0,
    refundTotalAmount:0,
    status: 0,
    notes: '测试',
    createBy: '毕建峰',
    createTime: new Date,
    updateBy: '毕建峰',
    updateTime:new Date,
    isDelete: 0,
    sourceSheet: 'string',
    typeId: 35,
    did: 0,
    uidStr: 'string',
    didStr: 'string',
    cidStr: 'string',
    details:SalesAdvanceRefundDetailList.value,
 })

  
 //有关核销的对象
 let writeoffDetailList=ref<WriteoffDetail[]>([])
 let writeoffTypeList=ref<WriteoffType[]>([])
 //加载核销类型
 let selectWriteoffType=async()=>{
    let response=await request.post("/cw/WriteOffController/selectWriteOffType")
    writeoffTypeList.value=response.data.data
    console.log(writeoffTypeList.value)
 }
 selectWriteoffType()


 //核销对象
 let writeOff=ref<WriteOff>({
    id: 0,
    docCode: 'string',
    docDate:new Date,
    cid: null,
    uid: 0,
    writeOffAmount: 0,
    targetType: 1,
    status: 0,
    notes: '核销测试',
    createBy: '毕建峰',
    createTime:new Date,
    updateBy: '毕建峰',
    updateTime:new Date,
    isDelete: 0,
    pid: null,
    did: null,
    typeId: 39,
    cidStr: 'string',
    uidStr: 'string',
    didStr: 'string',
    pidStr: 'string',
    details: writeoffDetailList.value,
    targetTypeStr: 'string',
    transferInCidStr: 'string',
    transferInPidStr: 'string',
    transferInCid: null,
    transferInPid: null,
 })

 let writeoffLink=ref<WriteoffLink>({
    fid: 0,
    writeoffCode: 'string',
    sourceCode: 'string',
    targetCode: 'string',
 })

 
 //部门情况
 const departments = ref([
   { value: 1, label: '销售部' },
   { value: 2, label: '技术部' },
   { value: 3, label: '财务部' }
 ])


 const rules = reactive({
   cid: [{ required: true, message: '请输入选择结算用户', trigger: 'blur' ,type:'number'}],
   docCode: [{ required: true, message: '请选择订单日期', trigger: 'change' }],
   bjName: [{ required: true, message: '请输入订单名称', trigger: 'blur' }],
   uid: [{ required: true, message: '请输入业务员ID', trigger: 'blur' }],
   did: [{ required: true, message: '请选择部门', trigger: 'change' }]
 })
 const disabledDate = (time: Date) => {
     return time.getTime() > Date.now()
 }
 // 修改handleAction方法
 const handleAction = (action:string) => {
   switch(action) {
     case 'choose':
       if (!salesAdvanceRefund.value.cid) {
         ElMessage.warning('请先选择客户')
         return
       }
       dialogVisible.value = true
        // 自动触发数据加载
        // searchSSalesAdvanceList()
       break
     case 'save-add':
     insertSalesClo()
       break;
     case 'history':
       
       break;
 
 
    
   }
 }

 const mainActions = ref([
   { 
     name: 'save', 
     label: '保存', 
     type: 'primary',
     icon: 'DocumentAdd'
   },
   {
     name: 'save-add',
     label: '保存新增',
     disabled: false
   },
   {
     name: 'audit',
     label: '审核',
     hidden: false
   },

   {
     name: 'history',
     label: '历史单据',
     badge: 3 // 角标数字
   }
 ])

 
 
 //访问方法并获取单据编号
 let getDocCode=async()=>{
   let response=await request.post('/xs/counter/addCode',{docType:'HXD'})
   docCode.value=response.data.data
   writeOff.value.docCode=docCode.value
    console.log(writeOff.value.docCode)
 }
 
 onMounted(async () => {
   await getDocCode()
 })
 
 // todo
 const generateUUID = () => {
     return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
     const r = (Math.random() * 16) | 0
     const v = c === 'x' ? r : (r & 0x3) | 0x8
     return v.toString(16)
   })
 }
 //动态加载客户
let customerList = ref<Customer[]>([])
let selectCustomer = async () => {
    let response = await request.post('/basic/Customer/selectAllCustomer')
    customerList.value = response.data.data
    console.log(customerList.value)

}
selectCustomer()

//查询业务员的方法
let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await request.post('/per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

let deptList=ref<Department[]>([])
let selectDept=async()=>{
  let response=await request.post('/per/dept/getAll')
  deptList.value=response.data.data
  console.log(deptList.value)
}
selectDept()

 //动态加载供应商
 let providerList=ref<PublicProvider[]>([])
 let selectProvider=async()=>{
 let response=await request.post('/basic/Provider/selectAllSupplier')
  providerList.value=response.data.data
  console.log(providerList.value)
}
selectProvider()


 
 const tableData = ref([{ 
   id: generateUUID(), 
   goodId:0,
   code: '',
   name:'',
   quantity: 1,
   actualPrice: 0,
   returnReason: '',
   tax: 13,
   taxIncludedPrice: 0,
   stock:100,
   unit: '件',
   kname:'测试',
   returnQuantity:0
 }])
 

 const newSelectedRows = ref<any[]>([])
 
 // 处理选中行变化
 const newHHandleSelectionChange = (selection: any[]) => {
   newSelectedRows.value = selection
 }
 
 // 删除选中行方法（添加确认对话框）
 const deleteSelectedRows = async () => {
   if (newSelectedRows.value.length === 0) {
     ElMessage.warning('请先选择要删除的行')
     return
   }
 
   try {
     await ElMessageBox.confirm(
       `确定要删除选中的 ${newSelectedRows.value.length} 行吗？`,
       '删除确认',
       {
         confirmButtonText: '确定',
         cancelButtonText: '取消',
         type: 'warning'
       }
     )
     // 通过ID过滤实现删除
     const selectedIds = new Set(newSelectedRows.value.map(row => row.id))
     tableData.value = tableData.value.filter(row => !selectedIds.has(row.id))
     ElMessage.success('删除成功')
   } catch (error) {
     ElMessage.info('已取消删除')
   }
 }
 
 

 
 //只读队列
 const readonlyColumns = [
   { prop: 'kname', label: '商品种类', width: 120 },
   { prop: 'suggestedPrice', label: '建议报价', width: 120 },
   { prop: 'taxIncludedPrice', label: '含税单价', width: 120 },
   { prop: 'tax', label: '增值税税率 (%)', width: 150 }
 ]

 //格式化金额显示
 const totalAmount = computed(() => {
   return tableData.value.reduce((sum, row) => {
     const price = Number(row.actualPrice) || 0
     const qty = Number(row.returnQuantity) || 0 // 关键修改点
     return sum + (price * qty)
   }, 0)
 })
 const formatTotal = computed(() => {
   return `¥${totalAmount.value.toFixed(2)}`
 })
 let PopupsPageNo=ref(1)
 let PopupsPageSize=ref(10) 
 const selectedCount = ref(0)
 const totalItems = ref(0)
 const dialogVisible = ref(false)
 const currentSelected =ref<SalesAdvance|null|SalesReceivable[]>()
 const selectedRows =ref<SalesAdvance[]|SalesReceivable[]>([])
 const searchForm = reactive({
     code: '',
   startDate: '',
   endDate: ''
 })
 // 表格选择处理
 const handleSelectionChange = (selection:any) => {
   selectedRows.value = selection
   selectedCount.value = selection.length
   if (selection.length > 0) {
     currentSelected.value = selection[0]
   } else {
     currentSelected.value = null
   }
 }
 const clearSelection = () => {
 
 }
 
 //分页方法
 let handlePageChange=()=>{
 
 }

type SourceOrder = {
  orderId: string;
  orderType: number;
  orderCode: string;
  orderDate: string;
  customerName: string;
  advanceAmount?: number;
  receivableAmount?: number;
  currentSettle: number;
  unsettledAmount:number,
  providerName?: string,
  payableAmount?: number; 

}

 let WriteOffList=ref<SalesAdvance[]|SalesReceivable[]>([])

 //不同源单类型
 let currentSourceType =ref<'receivable'|'advance'|'payable'|'prepay'>('advance');

 //区分两个不同的源单单据
 let sourceOrdersA =ref<SourceOrder[]>([])
 let sourceOrdersB =ref<SourceOrder[]>([])
 let sourceOrdersC = ref<SourceOrder[]>([]) // 应付单据数据
 let sourceOrdersD = ref<SourceOrder[]>([]) // 预付单据数据

 // 获取源单数据
 const searchSSalesAdvanceList = async (type:string) => {
   try {

    let res;

     const params = {
       docCode:searchForm.code,
       code: searchForm.code,
       startDate: searchForm.startDate,
       endDate: searchForm.endDate,
       pageNo: PopupsPageNo.value,
       pageSize: PopupsPageSize.value,
       cid:writeOff.value.cid,
       pid:writeOff.value.pid,
       typeId:5
     }
      if (type === 'receivable') {
      res = await request.post('/cw/SalesReceivableController/selectSalesReceivableByPage', params);
    } 
    else if (type === 'advance') {
      res = await request.post('/cw/SalesAdvanceController/selectSalesAdvanceByPage', params);
    } 
    else if (type === 'payable') {
      res = await request.post('/kc/inStore/getInStoreList', params);
    } 
    else if (type === 'prepay') {
      res = await request.post('/cw/YFK/getPage', params);
    }



     
     WriteOffList.value = res.data.data.list.map(item => {
      // 公共字段处理
      const baseFields = {
        id: item.id,
        docCode: item.code || item.docCode,
        docDate: item.orderDate || item.docDate,
        status: item.orderStatus ?? item.status,
        uid: item.businessmanName || item.storeManName || item.createBy,
        did: item.deptName || item.didStr,
        cid:item.cidStr 
      }

      // 按类型处理特殊字段
      switch(type) {
        case 'payable':
          return {
            ...baseFields,
            orderType: 4, // 应付单据类型
            supplierName: item.providerName,
            payableAmount: item.inStoreSumPrice,
            settledAmount: 0, // 应付单默认未核销
            unsettledAmount:item.providerName- item.inStoreSumPrice// 应付金额作为未核销金额
          }
        case 'advance':
          return {
            ...baseFields,
            orderType: 2, // 预收单据类型
            customerName: item.cidStr,
            advanceAmount: item.advanceAmount,
            settledAmount: item.settledAmount,
            unsettledAmount:item.advanceAmount- item.settledAmount
          }
        case 'receivable':
          return {
            ...baseFields,
            orderType: 3, // 应收单据类型
            customerName: item.cidStr,
            receivableAmount: item.totalAmount,
            settledAmount: item.settledAmount,
            unsettledAmount: item.totalAmount- item.settledAmount
          }
        default:
          return baseFields
      }
    })

     console.log("获取到的源单数据",WriteOffList.value)
     totalItems.value = res.data.data.total
   } catch (error) {
     console.error('查询失败:', error)
   }
 }



// 最大可核销金额计算
const getMaxSettle = (row: SourceOrder) => {
  if (currentSourceType.value === 'advance') {
    return row.unsettledAmount;
  }
   return row.unsettledAmount;
}
watch(() => writeOff.value.transferInCid, (newVal) => {
  if (writeOff.value.targetType === 4 && newVal === writeOff.value.cid) {
    ElMessage.warning('转入客户不能与原客户相同');
  }
});


// 源单类型映射
const getOrderType = (type: number) => {
  const typeMap: Record<number, string> = {
    1: '销售订单',
    2: '预收单据',
    3: '应收单据',
    4: '应付单据', 
    5: '预付单据'   
  };
  return typeMap[type] || '未知类型';
}




 const resetSearch = () => {
   searchForm.code = ''
   searchForm.startDate = ''
   searchForm.endDate = ''
   searchSSalesAdvanceList('receivable')
 }
 
 const confirmSelection = async() => {
    let targetOrders;
      switch(currentSourceType.value) {
    case 'advance': 
      targetOrders = sourceOrdersA;
      break;
    case 'receivable':
      targetOrders = sourceOrdersB;
      break;
    case 'payable':
      targetOrders = sourceOrdersC; // 新增应付数据目标
      break;
    case 'prepay':
      targetOrders = sourceOrdersD; // 新增预付数据目标
      break;
  }

  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条源单单')
    return
  }


  const existingIds = new Set(sourceOrders.value.map(o => o.orderId))
  const validOrders = selectedRows.value
    .filter(row => !existingIds.has(row.id))
    .map(row => {
      // 公共字段
      const baseOrder = {
        orderId: row.id,
        orderCode: row.docCode,
        orderDate: row.docDate,
        currentSettle: 0,
        settledAmount: row.settledAmount || 0,
        unsettledAmount: row.unsettledAmount || row.payableAmount
      }

      // 按类型处理特殊字段
      switch(currentSourceType.value) {
        case 'payable':
          return {
            ...baseOrder,
            orderType: 4,
            supplierName: row.supplierName,
            payableAmount: row.payableAmount
          }
        case 'advance':
          return {
            ...baseOrder,
            orderType: 2,
            customerName: row.customerName,
            advanceAmount: row.advanceAmount
          }
        case 'receivable':
          return {
            ...baseOrder,
            orderType: 3,
            customerName: row.customerName,
            receivableAmount: row.receivableAmount
          }
        default:
          return baseOrder
      }
    })

  

  targetOrders.value = [...targetOrders.value, ...validOrders]

 
 
  const tableRefreshKey = ref(0);
 watch(() => writeOff.value.targetType, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    // 清除所有相关源单数据
    sourceOrdersA.value = [];
    sourceOrdersB.value = [];
    sourceOrdersC.value = [];
    sourceOrdersD.value = [];
    
    // 清除表单关联数据（参考网页1）
    writeOff.value.transferInCid = null;
    writeOff.value.transferInPid = null;
    
    // 强制刷新表格
    tableRefreshKey.value++;
  }
});
  
  // 关闭对话框并重置选择
  dialogVisible.value = false
  selectedRows.value = []
  selectedCount.value = 0
  ElMessage.success(`成功添加${validOrders.length}条源单`)
  
 } 

    //校验核销金额必须相等
    const syncPaymentAmount = () => {
  // 计算预收应收总额
  const advanceTotal = sourceOrdersA.value.reduce((a,b) => a + b.currentSettle, 0);
  const receivableTotal = sourceOrdersB.value.reduce((a,b) => a + b.currentSettle, 0);
  
  // 金额不等时自动平衡（网页5正负核销逻辑）
  if (advanceTotal !== receivableTotal) {
    const diff = advanceTotal - receivableTotal;
    if (diff > 0) {
      sourceOrdersB.value.forEach(o => {
        o.currentSettle = Math.min(o.unsettledAmount, o.currentSettle + diff)
      })
    } else {
      sourceOrdersA.value.forEach(o => {
        o.currentSettle = Math.min(o.unsettledAmount, o.currentSettle - diff)
      })
    }
  }
}




//构造明细参数
 const generateDetails = () => {
  const allSources = [
    ...sourceOrdersA.value.map(order => ({
      ...order,
      sourceType: 2 // 预收单据类型编码
    })),
    ...sourceOrdersB.value.map(order => ({
      ...order,
      sourceType: 3 // 应收单据类型编码
    }))
  ]
 return allSources
    .filter(order => order.currentSettle > 0)
    .map((order): WriteoffDetail => ({
      id: 0, // 新增时ID由后端生成
      mainCode: writeOff.value.docCode, // 关联主单编号
      sourceType: order.sourceType, // 源单类型 2=预收 3=应收
      sourceSheet: order.orderCode, // 源单编号
      sourceSheetDetail: 1, // 默认明细行
      settledAmount: Number(order.currentSettle.toFixed(2)||0), // 本次核销金额
      unsettledAmount:Number(order.unsettledAmount.toFixed(2)||0), // 剩余未核销
      originAmount: order.sourceType === 2 
        ? order.advanceAmount || 0 
        : order.receivableAmount || 0, // 原始金额
      createBy: '当前用户', // 应从系统获取
      createTime: new Date(),
      updateBy: '当前用户',
      updateTime: new Date(),
      isDelete: 0 // 逻辑删除标识
    }))
};
                     
 const paymentAccounts = ref([
  {
    id: 1,
    accountName: '招行',
    paymentMethod: '银行转账',
    amount: 0,
    fee: 0,
    transactionNo: '',
    remark: ''
  }
])


// 新增源单信息相关数据
const sourceOrders = ref<any[]>([])
const sourceDialogVisible = ref(false)

// 计算属性
const formatPaymentTotal = computed(() => {
  const total = paymentAccounts.value.reduce(
    (sum, row) => sum + Number(row.amount) - Number(row.fee),
    0
  )
  return `¥${total.toFixed(2)}`
})

// 新增方法
const selectSourceOrder = (type:'receivable'|'advance'|'payable'|'prepay') => {
  currentSourceType.value = type
  dialogVisible.value = true  // 打开弹窗
  searchSSalesAdvanceList(type) // 触发数据加载
}




// 净收款金额计算
const netCollectionAmount = computed(() => {
  return paymentAccounts.value.reduce((sum, row) => 
    sum + (Number(row.amount) || 0) - (Number(row.fee) || 0), 0);
});

watch(netCollectionAmount, (newVal) => {
  const totalAdvance = sourceOrders.value.reduce((sum, order) => sum + order.currentAdvance, 0)
  
  // 金额变动时自动同步到源单（网页5双向绑定原理）
  if (Math.abs(newVal - totalAdvance) > 0.01) {
    const perOrderAdvance = newVal / sourceOrders.value.length
    sourceOrders.value.forEach(order => {
      order.currentAdvance = Math.min(perOrderAdvance, order.advanceAmount)
    })
  }
})




// 移除源单
const removeSourceOrder = (row: SourceOrder, type: 'advance' | 'receivable') => {
  if (type === 'advance') {
    sourceOrdersA.value = sourceOrdersA.value.filter(o => o.orderId !== row.orderId);
  } else {
    sourceOrdersB.value = sourceOrdersB.value.filter(o => o.orderId !== row.orderId);
  }
}

 //点击新增后新增收款单
 let insertSalesClo =async()=>{ 
  // 获取核销总额
  const advanceTotal = sourceOrdersA.value.reduce((a,b) => a + b.currentSettle, 0)
  const receivableTotal = sourceOrdersB.value.reduce((a,b) => a + b.currentSettle, 0)
  
  // // 金额不等时阻断提交（网页7自动核销前提）
  // if (advanceTotal !== receivableTotal) {
  //   ElMessage.error('预收与应收核销总额必须相等')
  //   return
  // }

  // 构造明细数据
  const details = generateDetails()
  const totalSettle = [
    ...sourceOrdersA.value,
    ...sourceOrdersB.value
  ].reduce((sum, order) => sum + (order.currentSettle || 0), 0);

    writeOff.value.targetType=1
    writeOff.value.writeOffAmount=advanceTotal
    writeoffLink.value = {
    fid:0,
    writeoffCode: writeOff.value.docCode,
    sourceCode: sourceOrdersA.value[0]?.orderCode || '', // 预收单据编号
    targetCode: sourceOrdersB.value[0]?.orderCode || '' // 应收单据编号
  }
  // 更新主单收款总额
    let response=await request.post("/cw/WriteOffController/insertWriteOff",{
        writeoffLink:writeoffLink.value,
        writeOff:writeOff.value,
        details:details
    })

    let saleReceivable=ref(WriteOffList.value[0])
    saleReceivable.value.cid=writeOff.value.transferInCid
    //如果是应收转应收

    if(writeOff.value.targetType==4){
    await request.post('/cw/SalesReceivableController/insertSalesReceivable',saleReceivable.value)
    }
    if(response.data.code=='200'){
      ElMessage.success("新增成功")
      router.push("/home/salesAdvanceRefundInfo")
    }else{
      ElMessage.error("新增失败")
    }
 }
 
 </script>
 
 
 <style scoped>
 .el-row {
     margin-bottom: 20px;
 }
 
 .el-row:last-child {
     margin-bottom: 0;
 }
 
 .el-col {
     border-radius: 4px;
 }
 
 .grid-content {
     border-radius: 4px;
     min-height: 36px;
 }
 .required-label::after {
   content: "*";
   color: #f56c6c;
   margin-left: 4px;
 }
 
 .goods-table {
   margin-top: 20px;
 }
 
 .toolbar {
   margin-bottom: 15px;
   padding: 10px;
   background: #f5f7fa;
   border-radius: 4px;
 }
 
 .el-table :deep(.el-input__inner) {
   text-align: center;
 }
 .total-summary {
   background: #fff8dc; /* 浅黄色背景 */
   padding: 12px 20px;
   display: flex;
   justify-content: flex-end;
   border: 1px solid #ebeef5;
   border-top: none;
 }
 
 .total-label {
   font-weight: 600;
   color: #606266;
   margin-right: 30px;
 }
 
 .total-amount {
   color: #f56c6c;
   min-width: 120px;
   text-align: right;
   font-family: Arial, sans-serif;
 }
 .pagination-wrapper {
     margin-top: 16px;
     display: flex;
     justify-content: flex-end;
 }
 .dialog-header {
   display: flex;
   align-items: center;
   margin-bottom: 15px;
   flex-wrap: wrap;
   gap: 10px;
 }
 
 .date-label {
   color: #606266;
   margin: 0 10px;
 }
 
 .date-separator {
   margin: 0 8px;
   color: #c0c4cc;
 }
 
 .selected-info {
   margin: 12px 0;
   display: flex;
   align-items: center;
   gap: 10px;
   color: #606266;
 }
 
 .dialog-footer {
   display: flex;
   justify-content: space-between;
   align-items: center;
   margin-top: 15px;
 }
 
 .pagination-info {
   color: #606266;
 }
 
 .action-buttons {
   display: flex;
   gap: 15px;
 }
 
 :deep(.el-dialog__header) {
   border-bottom: 1px solid #ebeef5;
 }

 .collection-info {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.source-info {
  margin-top: 20px;
  border-top: 2px solid #ebeef5;
  padding-top: 15px;
}

.toolbar {
  margin-bottom: 15px;
}

.total-summary {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 15px;
  padding: 10px;
  background: #f4f4f5;
  border-radius: 4px;
}

.total-label {
  font-weight: 600;
  margin-right: 20px;
}

.total-amount {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
}
.validation-info {
  margin: 15px 0;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
}

.amount-summary {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

.el-alert {
  margin-bottom: 10px;
}
 </style>







